#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QGridLayout>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLineEdit>
#include <QHeaderView>
#include <QStyleFactory>
#include <QDebug>
#include <QSettings>
#include <QMessageBox>
#include <QFrame>
#include <QDateTime>
#include "customitemdelegate.h"
#include "customtabview.h"
#include <QFileIconProvider>
#include <QTemporaryFile>
#include <QProcess>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    this->setWindowTitle(QString("文件浏览工具 --老人与海 %1").arg(STR_VERSION));

    m_spl_Horizontal=new  QSplitter(Qt::Horizontal);
    m_spl_Vertical=new QSplitter(Qt::Vertical);

    QFrame *m_line = new QFrame(this);
    m_line->setFrameShape(QFrame::HLine);

    QVBoxLayout *V_layout=new QVBoxLayout();
    V_layout->addWidget(m_line);
    V_layout->addWidget(m_spl_Horizontal);
    ui->centralwidget->setLayout(V_layout);

    this->fun_ViewInit();
    this->fun_DataInit();
}

MainWindow::~MainWindow()
{
    qDebug()<<"~MainWindow()";
    delete ui;
}

void MainWindow::fun_ViewInit()
{
    m_treeView=new MyTreeView();
   // m_treeView->setMaximumWidth(220);
    m_treeView->setMinimumWidth(230);
    m_treeView->setSelectionMode(QTreeView::SingleSelection);        //单选，配合上面的整行就是一次选单行
    m_treeView->header()->setStretchLastSection(true);//单选，配合上面的整行就是一次选单行//单选，配合上面的整行就是一次选单行
    m_treeView->setSelectionBehavior(QTreeView::SelectRows);			//一次选中整行
    m_treeView->setFocusPolicy(Qt::NoFocus);                  //去掉鼠标移到单元格上时的虚线框
    m_treeView->setLineWidth(1);
    m_treeView->setStyle(QStyleFactory::create("windows"));
    connect(m_treeView,&MyTreeView::sig_clickedDoubel,this,&MainWindow::slots_TreeviewDoubleClicked);
    connect(m_treeView,&MyTreeView::expanded,this,&MainWindow::slots_expanded);

    QStringList HeaderList;
    HeaderList<<tr("分类");
    m_treeModel=new TreeModel(HeaderList,this);
    m_treeView->header()->hide();
    m_treeView->setModel(m_treeModel);

    m_tabView=new CustomTabView();
    m_tabView->verticalHeader()->hide();
    m_tabView->horizontalHeader()->setStretchLastSection(true); //行头自适应表格
    m_tabView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//自动适应表项宽度
    m_tabModel=new CustomModel(this);
    customItemDelegate* Delegate = new customItemDelegate(m_tabView,m_tabModel);
    connect(Delegate,&customItemDelegate::sig_btnClicked,this,&MainWindow::slots_btnClicked);
    m_tabView->setItemDelegate(Delegate);
    m_tabView->setModel(m_tabModel);

    m_spl_Horizontal->addWidget(m_treeView);
    m_spl_Horizontal->addWidget(m_spl_Vertical);
    m_spl_Horizontal->setStretchFactor(0,2);
    m_spl_Horizontal->setStretchFactor(1,8);
    m_spl_Vertical->addWidget(m_tabView);
    m_spl_Vertical->setStretchFactor(0,8);
    m_spl_Vertical->setStretchFactor(1,2);
}

void MainWindow::fun_DataInit()
{
    TreeItem* root = m_treeModel->root();
    fun_getRootFileList(root);
}


void MainWindow::fun_getRootFileList(TreeItem *ParentItem)
{
    if(ParentItem==nullptr){
        return ;
    }
    foreach (QFileInfo my_info, QDir::drives())
    {
        _DATA_STRUCT fileInfor;
        fileInfor.strFileName=my_info.absoluteFilePath();
        fileInfor.strPath=my_info.absoluteFilePath();
        fileInfor.intFileSize=my_info.size();
        fileInfor._Icon=getFileIcon(my_info);

        fun_Creator_ChildNode(ParentItem,fileInfor);
       // qDebug()<<fileInfor.strFileName<<fileInfor.strPath<<fileInfor.intFileSize;
    }

    for(int i=0;i<ParentItem->childCount();i++){
        TreeItem *Item_Child=ParentItem->child(i);
        if(Item_Child->m_IsLoad==false){
            Item_Child->m_IsLoad=true;
            fun_getChildFileList(Item_Child,Item_Child->getData()->strPath);
        }
    }

    return ;
}

void MainWindow::fun_getChildFileList(TreeItem *ParentItem, QString Path)
{
    if(ParentItem==nullptr){
        return ;
    }
    //qDebug()<<"Path"<<Path;
    QStringList filePathList;
    QDir dirPath(Path);
    QStringList format;
        format<<"*";

    QList<QFileInfo> file(dirPath.entryInfoList(format,QDir::AllDirs|QDir::Files,QDir::NoSort));
    for(int i=0;i<file.count();i++)
    {
        //过来当前目录和上一级目录
        if(file[i].fileName().indexOf(".")==0){
            continue;
        }
        if(file[i].fileName().indexOf("..")==0){
            continue;
        }
        _DATA_STRUCT fileInfor;
        fileInfor.strFileName=file[i].fileName();
        fileInfor.strPath=file[i].absoluteFilePath();
        fileInfor.intFileSize=file[i].size();

        fileInfor._Icon=getFileIcon(file[i]);
        fun_Creator_ChildNode(ParentItem,fileInfor);
        //qDebug()<<fileInfor.strFileName<<fileInfor.strPath<<fileInfor.intFileSize;
    }
    return ;
}

void MainWindow::fun_Creator_ChildNode(TreeItem *parent, const _DATA_STRUCT &data)
{
    //qDebug()<<"fun_Creator_ChildNode";
    _DATA_STRUCT *Child_data=new _DATA_STRUCT;
    *Child_data=data;

    TreeItem* Child_Node = new TreeItem(parent); //指定父节点
    Child_Node->setPtr(Child_data);
    parent->appendChild(Child_Node); //添加子节点
}

QIcon MainWindow::getFileIcon(QFileInfo &fileInfor)
{
    QIcon RetIcon;
    QFileIconProvider icon;
    return icon.icon(fileInfor);

}
void MainWindow::slots_TreeviewDoubleClicked()
{
//    QModelIndex index=m_treeView->currentIndex();
//    this->slots_expanded(index);
}

void MainWindow::slots_expanded(const QModelIndex &index)
{
    if(index.isValid()==false){ return; }

    //获取张开节点的子节点的下一节点
    TreeItem *Item=m_treeModel->itemFromIndex(index);
    for(int i=0;i<Item->childCount();i++)
    {
        TreeItem *Item_Child=Item->child(i);
        if(Item_Child->m_IsLoad==false)
        {
            Item_Child->m_IsLoad=true;
            fun_getChildFileList(Item_Child,Item_Child->getData()->strPath);
        }
    }
    emit m_treeModel->layoutChanged();

    QModelIndex indexTab=m_tabView->currentIndex();
    m_tabView->closePersistentEditor(indexTab);//关闭打开的编辑控件，不然不同的数据不同的代理控件会倒置段错误
    m_tabModel->fun_clearData();
    m_tabModel->fun_HederInit();
    for(int row=0;row<Item->childCount();row++){
        _DATA_STRUCT *Data=Item->child(row)->getData();
        m_tabModel->fun_addDataRow(*Data);
    }

    emit m_tabModel->layoutChanged();
    m_tabView->resizeColumnToContents(2);//根据内容自动适应宽度
}

void MainWindow::slots_btnClicked(const QModelIndex index)
{

    _DATA_STRUCT  data=m_tabModel->fun_GetDataItem(index);

//    QProcess::startDetached(QString("start %1").arg(data.strPath));

//    QProcess m_Process;
//    QString StrCmd=QString("start %1").arg(data.strPath);
//    m_Process.start(StrCmd);
//    QString StrError;
//    QString StrResults;
//    if(!m_Process.waitForFinished(5000))
//    {
//        StrError=m_Process.readAllStandardError();
//        qDebug()<<"CMD_RunTmpShell->"<<StrError;

//    }
//    StrResults=m_Process.readAllStandardOutput();
//    m_Process.close();

//    qDebug()<<"slots_btnClicked"<<data.strPath<<StrCmd<<StrResults<<endl;

    QString StrCmd=QString("start %1").arg(data.strPath);
    system(StrCmd.toLocal8Bit());
   // qDebug()<<"slots_btnClicked"<<data.strPath<<endl;
}

void MainWindow::changeEvent(QEvent *event)
{
    if(event->type()==QEvent::LanguageChange)
    {
        //this->slots_SetSubText();
    }
    else
    {
         QWidget::changeEvent(event);
    }
}

